<?php
namespace App\Console\Commands;

use App\Models\LoanApply;
use App\Models\RepaySummary;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;

class DataRepair extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'data_repair:loan_apply';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'Command description';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $list= DB::select("select loan_request_id,loan_id,count(id) num from loan_apply where loan_id is not null and loan_id !='0'  GROUP BY loan_id having num>1");
        if($list) {
            foreach ($list as $v) {
                $summary = RepaySummary::select('loan_request_id')->where('loan_id',$v->loan_id)->first();
                //有初始化还款数据、保留相关联的最新的一条数据
                if($summary) {
                    $loan_request_id = $summary->loan_request_id;
                    $loan = LoanApply::select('id')
                        ->where('loan_request_id',$loan_request_id)
                        ->where('loan_status',2)
                        ->orderByDesc('id')
                        ->first();
                    if($loan) {
                        Log::debug("有Summary记录loan_id:{$v->loan_id} loan_request_id:{$v->loan_request_id} loan_applay表ID:{$loan->id}");
                        LoanApply::where('id','<>',$loan->id)->where('loan_request_id',$v->loan_request_id)->delete();
                    }
                    //没有  保留最新的一条数据
                } else {
                    $loan = LoanApply::select('id')->where('loan_id',$v->loan_id)->orderByDesc('id')->first();
                    if($loan) {
                        Log::debug("没有Summary记录loan_idloan_id:{$v->loan_id} loan_request_id:{$v->loan_request_id} loan_applay表ID:{$loan->id}");
                        LoanApply::where('id','<>',$loan->id)->where('loan_request_id',$v->loan_request_id)->delete();
                    }
                }
            }
        }
    }
}
